//
//  NNSegmentTool.swift
//  DYLive
//
//  Created by 众力金融 on 2019/5/6.
//  Copyright © 2019 众力金融. All rights reserved.
//

import UIKit

open class NNSegmentTool: UIView, UIScrollViewDelegate,UIGestureRecognizerDelegate {
    ///控制器数组
    open var subViewControllers = [UIViewController]()
    /// title字体是否缩放
    open var isTitleZoomEnabled: Bool = false
    ///titleLabel缩放的比例
    open var titleSelectedScale: CGFloat = 0.2
    ///label宽度
    open var titleLabelWidth: CGFloat = 0.0
    ///默认选择第几个
    open var selectedPosition: Int = 0
    ///label的字体
    open var titleNormalFont: CGFloat = 13.0

    //红色指示器
    fileprivate var indicatorView = UIView()
    //底部ScrollView
    fileprivate var contentView = UIScrollView()
     //顶部ScrollView
    fileprivate var titlesView = UIScrollView()
     //顶部ScrollView子控件的tag
    fileprivate static let titleViewTag = 1000;
    
    override public init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    func refer() {
        
    // 底部的scrollView
     setupContentView()
    //title展示
     setupTitlesView()
    }
    
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    func setupTitlesView() {
        // 标签栏整体
        titlesView.backgroundColor = .white
        titlesView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 35)
        titlesView.showsHorizontalScrollIndicator = false
        self.addSubview(titlesView)
        
        indicatorView.backgroundColor = .red
        indicatorView.tag = -1
        indicatorView.height = 2
        indicatorView.y = titlesView.height - indicatorView.height
        
        let LabelWidth: CGFloat = titleLabelWidth
        let LaeblHeight: CGFloat = titlesView.height
        
        for i in 0..<subViewControllers.count {
            
            let label = NNSegmentLabel()
            let vc = subViewControllers[i]
            label.text = vc.title
            label.width = LabelWidth
            label.height = LaeblHeight
            label.y = 0
            label.x = CGFloat(CGFloat(i) * LabelWidth)
            let tap = UITapGestureRecognizer()
            tap.addTarget(self, action: #selector(buttonCLick(_:)))
            label.addGestureRecognizer(tap)
            label.tag = i + NNSegmentTool.titleViewTag
            label.LabelIsTitleZoomEnabled = isTitleZoomEnabled
            label.titleSelectedScale = titleSelectedScale
            label.font = .systemFont(ofSize: titleNormalFont)
            titlesView.addSubview(label)
            
            if i == selectedPosition {
                
                label.scale(scale: 1.0)
                let labelSize = label.text!.size(withAttributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: titleNormalFont)])
                 print(labelSize.height)
                indicatorView.width = labelSize.width
                indicatorView.centerX = label.centerX
                //滚动scrollView
                var offset: CGPoint = contentView.contentOffset
                offset.x = CGFloat(label.tag - NNSegmentTool.titleViewTag) * self.bounds.size.width
                contentView.setContentOffset(offset, animated: true)
            }

        }
       titlesView.contentSize = CGSize(width: (LabelWidth * CGFloat(subViewControllers.count)), height: 0.0)
       titlesView.addSubview(indicatorView)
    }
    
    @objc func buttonCLick(_ tap:UITapGestureRecognizer) {
        
        let index: Int = tap.view?.tag ?? 0
        var offset: CGPoint = contentView.contentOffset
        offset.x = CGFloat(index - NNSegmentTool.titleViewTag) * contentView.width
        contentView.setContentOffset(offset, animated: true)
        
    }
    // MARK: - 底部的scrollView
    
    func setupContentView() {
        contentView.frame = self.bounds
        contentView.delegate = self
        contentView.isPagingEnabled = true
        contentView.showsVerticalScrollIndicator = false
        contentView.showsHorizontalScrollIndicator = false
        self.insertSubview(contentView, at: 0)
        contentView.contentSize = CGSize(width: Int(contentView.width) * subViewControllers.count, height: 0)
        scrollViewDidEndScrollingAnimation(contentView)
    }
    // MARK: - <UIScrollViewDelegate>
    /**
     * scrollView结束了滚动动画以后就会调用这个方法（比如- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated;方法执行的动画完毕后）
     */
  public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        
    let index: Int = Int(scrollView.contentOffset.x / scrollView.width)
    let vc = subViewControllers[index]
    if vc.isViewLoaded {return}
    vc.view.frame = CGRect(x: scrollView.contentOffset.x, y: 0, width: scrollView.width, height: scrollView.height)
    scrollView.addSubview(vc.view)

    }
    /**
     * 手指松开scrollView后，scrollView停止减速完毕就会调用这个
     */
   public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        scrollViewDidEndScrollingAnimation(scrollView)
    }
    /**
     * 只要scrollView在滚动，就会调用
     */
   public func scrollViewDidScroll(_ scrollView: UIScrollView) {

    let scale = scrollView.contentOffset.x / scrollView.width
    
    //处理边界的情况
    if scale < 0 || scale > CGFloat(subViewControllers.count - 1) {
        return
    }
    
    //获得需要操作的左边Label
    let leftIndex = Int(scale)
    let leftLabel = titlesView.viewWithTag(leftIndex + NNSegmentTool.titleViewTag) as! NNSegmentLabel
    // 获得需要操作的右边label
    let rightIndex = leftIndex + 1
    var rightLabel:NNSegmentLabel?
    if (rightIndex == subViewControllers.count) {
        rightLabel = nil
    }else {
        rightLabel = titlesView.viewWithTag(rightIndex + NNSegmentTool.titleViewTag) as? NNSegmentLabel
    }
    // 右边比例
    let rightScale = scale - CGFloat(leftIndex)
    // 左边比例
    let leftScale = 1 - rightScale;
    leftLabel.scale(scale: leftScale)
    rightLabel?.scale(scale: rightScale)
    
    let labelSize = leftLabel.text!.size(withAttributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: titleNormalFont)])
    let lineBottomDis = (leftLabel.bounds.size.width - labelSize.width) / 2
    
    indicatorView.frame = CGRect(x: scale * leftLabel.bounds.size.width + lineBottomDis, y: titlesView.height - indicatorView.height, width: labelSize.width, height: 2)
    
    }
}
